package cn.yitun.chat.yitunchatnettysdk.netty.tcp;

import cn.yitun.chat.yitunchatbasesdk.server.im.dispatcher.handler.SessionHandler;
import cn.yitun.chat.yitunchatbasesdk.server.im.dispatcher.handler.SessionMessageHandler;
import cn.yitun.chat.yitunchatnettysdk.netty.common.session.ChannelSession;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SocketHandler extends SimpleChannelInboundHandler<Object> {

	protected final Logger logger = LoggerFactory.getLogger(this.getClass());
	private SessionMessageHandler messageHandler;
	private SessionHandler sessionHandler;
	private ChannelSession channelSession;

	public SocketHandler(SessionMessageHandler messageHandler, SessionHandler sessionHandler) {
		this.messageHandler = messageHandler;
		this.sessionHandler = sessionHandler;
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Object frame) throws Exception {
		if (frame instanceof String) {
			String message = ((String) frame);
			messageHandler.onMessage(message, channelSession);
		}
	}

	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		channelSession = new ChannelSession(ctx);
		if (logger.isDebugEnabled()) {
			String session = channelSession != null ? (channelSession.getRemoteAddress() + "/" + channelSession.getRemotePort()) : "";
			logger.debug("handlerAdded:" + session);
		}
	}

	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		sessionHandler.removeSession(channelSession);
		if (logger.isDebugEnabled()) {
			String session = channelSession != null ? (channelSession.getRemoteAddress() + "/" + channelSession.getRemotePort()) : "";
			String key = channelSession != null ? channelSession.getKey().toString() : "";
			logger.debug("handlerRemoved:" + session + "/" + key);
		}
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("channelActive");
		}
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("channelInactive");
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		// ctx.close();
	}
}
